package com.biz.primus.ms.base.api;

import com.biz.primus.base.constant.StatusCodes;
import com.biz.primus.base.exception.BizException;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;

import static com.biz.primus.base.constant.SoaExceptionFieldNames.ERROR_CODE;
import static com.biz.primus.base.constant.SoaExceptionFieldNames.ERROR_MESSAGE;

public class BaseApiController {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(Exception.class)
    protected void exceptionHandler(Exception ex, HttpServletResponse response) {

        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        if (ex instanceof BizException) {
            response.addHeader(ERROR_CODE, String.valueOf(((BizException) ex).getCode()));
            response.addHeader(ERROR_MESSAGE, ((BizException) ex).getDescription());
        } else {
            logger.warn("unprocessed exception.", ex);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.addHeader(ERROR_CODE, String.valueOf(StatusCodes.COMMON_INTERNAL_EXCEPTION));
            response.addHeader(ERROR_MESSAGE, ex.getMessage());
        }
    }
}